package cn.lf.android.lawfirm.inputsource;

import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import cn.lf.android.lawfirm.OrdinaryBaseActivity;
import cn.lf.android.lawfirm.R;
import cn.lf.android.lawfirm.inputsource.conntroller.QuasiCommissionedPartyConntroller;
import cn.lf.android.lawfirm.inputsource.model.QuasiCommissionedPartyEntity;
import cn.lf.android.lawfirm.inputsource.view.QuasiCommissionedPartyAdapter;
import cn.lf.android.lawfirm.utils.DebugLog;
import cn.lf.android.lawfirm.utils.JsonBeans;
import cn.lf.android.lawfirm.utils.SPUtil;
import cn.lf.android.lawfirm.view.NoScrollListView;

/**
 * 拟委托方页
 * Created by Administrator on 2017/8/6.
 */

public class QuasiCommissionedPartyActivity extends OrdinaryBaseActivity
        implements AdapterView.OnItemClickListener {

    private QuasiCommissionedPartyConntroller mConntroller;
    private ListView mListView;
    private QuasiCommissionedPartyEntity mEntitiy;
    private QuasiCommissionedPartyAdapter mAdapter;
    private List<QuasiCommissionedPartyEntity> mList;

    @Override
    public int getChildView() {
        return R.layout.activity_quasi_commissioned_party;
    }

    @Override
    public void initViewId() {
        initTitle();
        initSearch();
        addTextChangeWatcher();
        mListView = ((ListView) findId(R.id.noScrollLV));
        mSearch.setHint("请输入拟委托方姓名");
    }

    @Override
    public void initData() {
        //搜索框的×，是用来清除搜索框数据的
        isClearText(true);
        mClean.setOnClickListener(this);
        mConntroller = new QuasiCommissionedPartyConntroller(quasiCommissionedPartyCallback);
        mList = new ArrayList<QuasiCommissionedPartyEntity>();
        mAdapter = new QuasiCommissionedPartyAdapter(QuasiCommissionedPartyActivity.this, mList);
        mListView.setScrollbarFadingEnabled(false);//不滚动的时候隐藏快滚条
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);
    }

    private void addTextChangeWatcher() {
        mSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //这里是联通的，有变化就进行网络请求
                if (mSearch.getText().toString().trim().length() == 0) {
                    mClean.setVisibility(View.GONE);
                    mSelectBtn.setVisibility(View.GONE);
                    mList.clear();
                    mAdapter.notifyDataSetChanged();
                    return;
                } else {
                    mClean.setVisibility(View.VISIBLE);
                    mSelectBtn.setVisibility(View.GONE);
                }
                SPUtil sp = new SPUtil(mActivity);
                String accessToken = sp.getAccessToken();
                mConntroller.onQuasicommissionedParty(accessToken, mSearch.getText().toString().trim());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void initSearch() {
        mSearchLayout.setVisibility(View.VISIBLE);
        mClean.setVisibility(View.GONE);
        mSelectBtn.setOnClickListener(this);
        mSearch.setOnKeyListener(onKeyListener);// 键盘搜索按钮监听
    }

    private void initTitle() {

        mImgLeft.setVisibility(View.VISIBLE);
        mImgLeft.setOnClickListener(this);
        mTitle.setText("拟委托方");
    }

    /**
     * 点击屏幕重新加载
     */
    @Override
    public void refreshLoad() {

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {
            case R.id.img_left:
                hintKbTwo();
                finish();
                break;
            case R.id.select:
                hintKbTwo();
                Intent intent = new Intent();
//                    * cusID字段：客户编号（int）
//                    * name字段：客户名称（string）
//                    * type字段：客户类型（int）
//                    * linkmen字段：联系人（string）
//                    * linkTel字段：联系电话（string）
                intent.putExtra("name", mSearch.getText().toString());
                intent.putExtra("cusID", "");
                intent.putExtra("linkmen", "");
                intent.putExtra("type", "");
                intent.putExtra("linkTel", "");
                setResult(123, intent);
                finish();
                break;
            case R.id.imgClean:
                hintKbTwo();
                mSearch.setText("");
                break;
            default:
                break;
        }
    }

    // EditText键盘上搜索键监听
    View.OnKeyListener onKeyListener = new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (!isNetWorkConnected()) {
                showUnNetWork();
            }
            if (keyCode == KeyEvent.KEYCODE_ENTER
                    && event.getAction() == KeyEvent.ACTION_DOWN) {
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(QuasiCommissionedPartyActivity.this
                                        .getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);

                mSearch.clearFocus();
            }
            return false;
        }
    };

    /**
     * 请求你委托方回调
     */
    QuasiCommissionedPartyConntroller.QuasiCommissionedPartyCallback quasiCommissionedPartyCallback = new QuasiCommissionedPartyConntroller.QuasiCommissionedPartyCallback() {
        @Override
        public void onSuccessed(Boolean isSuc, JSONArray jsonArray, String errorMsg) {
            if (isSuc) {
                List<QuasiCommissionedPartyEntity> beans = JsonBeans.getJsonList(jsonArray.toString(),
                        new TypeToken<List<QuasiCommissionedPartyEntity>>() {
                        });
                mList.clear();
                mList.addAll(beans);
                mAdapter.notifyDataSetChanged();
            } else {
            }
        }

        @Override
        public void onFailed(String errorMsg) {
        }
    };

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //点击条目，将数据带回前一页
        DebugLog.e("----i---" + i);
        DebugLog.e("------mList.get(i)------" + mList.get(i));
        hintKbTwo();
        Intent intent = new Intent();
//                    * cusID字段：客户编号（int）
//                    * name字段：客户名称（string）
//                    * type字段：客户类型（int）
//                    * linkmen字段：联系人（string）
//                    * linkTel字段：联系电话（string）
        DebugLog.e("name8==" + mList.get(i).getName());
        DebugLog.e("cusID8==" + mList.get(i).getCusID());
        DebugLog.e("linkmen8==" + mList.get(i).getLinkmen());
        DebugLog.e("type8==" + mList.get(i).getType());
        DebugLog.e("linkTel8==" + mList.get(i).getLinkTel());

        intent.putExtra("name", mList.get(i).getName());
        intent.putExtra("cusID", mList.get(i).getCusID());
        intent.putExtra("linkmen", mList.get(i).getLinkmen());
        intent.putExtra("type", mList.get(i).getType());
        intent.putExtra("linkTel", mList.get(i).getLinkTel());
//        intent.putExtra("QuasiCommissionedPartyEntity", mList.get(i));
        DebugLog.e("------.get(i).getCusID()------" + mList.get(i).getCusID());
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

}
